<template>
  <div class="container">
    <nav-bar title="登录" :cartShow="false" />
    <!-- <div class="tabs">
      <div class="tab" :class="{'tab-cur': loginType === 1}" @click="tabSwitch(1)">手机</div>
      <div class="tab" :class="{'tab-cur': loginType === 2}" @click="tabSwitch(2)">邮箱</div>
    </div> -->
    <!-- 手机登录 -->
    <div class="form form-phone" v-show="loginType === 1">
      <div class="title">登录</div>
      <div class="ipt ipt-phone">
        <!-- <div class="country-num">+86</div> -->
        <input type="text" placeholder="手机号码或运营商账号" @input="phoneChange" :value="phone" />
      </div>
      <div class="ipt ipt-email">
        <input type="password" placeholder="密码" @input="phonePasswordChange" :value="phonePassword" />
      </div>
      <div class="form-btns">
        <div class="form-btn" :class="{'btn-bg': passVerify}" @click="login">
          {{wxInfo ? '绑定我的账户' : '登录'}}
        </div>
        <div v-if="wxInfo" class="form-btn form-btn-new" @click="goToBind">我是新会员</div>
      </div>
      <div class="tips" @click="goToRegister">
        忘记密码?
      </div>
    </div>
    <!-- 邮箱登录 -->
    <div class="form form-phone" v-show="loginType === 2">
      <div class="ipt ipt-email">
        <input type="text" placeholder="邮箱地址" @input="emailChange" :value="email" />
      </div>
      <div class="ipt ipt-email">
        <input type="password" placeholder="密码" @input="emailPasswordChange" :value="emailPassword" />
      </div>
      <div class="form-btns">
        <div class="form-btn" :class="{'btn-bg': passVerify}" @click="login">登录</div>
      </div>
      <div class="tips">
        忘记密码?
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from 'components/common/NavBar'
import { Toast } from 'vant'
import { request } from '../../utils'
import { getUserDetail, getUserDetailById, loginOrBindUser, getBindInfo } from '../../network/user'
import { applyBelong } from '../../network/belong'


export default {
  components: {
    NavBar
  },
  data(){
    return {
      loginType: 1,
      phone: '',
      phonePassword: '',
      email: '',
      emailPassword: '',
      wxInfo: JSON.parse(localStorage.getItem("wxInfo")),
    }
  },
  computed: {
    passVerify(){
      let flag = false
      if(this.loginType === 1){
        flag = this.phone !== '' && this.phonePassword !== ''
      } else {
        flag = this.email !== '' && this.emailPassword !== ''
      }
      return flag
    }
  },
  methods: {
    goToBind(){
      this.$router.push('/regnewPhone')
    },
    tabSwitch(index){
      this.loginType = index
    },
    phoneChange(e){
      this.phone = e.target.value
    },
    phonePasswordChange(e){
      this.phonePassword = e.target.value
    },
    emailChange(e){
      this.email = e.target.value
    },
    emailPasswordChange(e){
      this.emailPassword = e.target.value
    },
    login(){
      if(!this.passVerify){
        Toast('账号密码不能为空')
      } else {
        this.requestLogin(() => {
          Toast({
            message: this.wxInfo ? '绑定成功' : '登录成功',
            duration: 1000
          })
          setTimeout(() => {
            localStorage.setItem('phone', this.phone)
            localStorage.setItem('phonePassword', this.phonePassword)
            if(sessionStorage.getItem('goAfterLogin') === 'coupon'){
              this.$router.push({
                path: '/coupon',
                query: {
                  id: sessionStorage.getItem('shareCoupons')
                }
              })
            } else {
              this.$router.push('/best')
            }
          }, 1000)
        })
      }
    },
    async requestLogin(cb){
      let requestData = {}
      // 判断是手机登录还是邮箱登录
      if(this.loginType === 1){ // 手机登录
        requestData = {
          userName: this.phone,
          password: this.phonePassword
        }
      }
      // 如果从微信登录过来(存在微信信息)，增加微信信息用于绑定手机
      let wxInfo = this.wxInfo
      let isBind = await this.toGetBindInfo(this.phone)
      if(wxInfo && !isBind){ // 微信授权、手机号未绑定微信
        // 微信用户信息
        let requestDataWx = {
          oauthNickName: wxInfo.nickname,
          oauthType: 'Himall.Plugin.OAuth.WeiXin',
          oauthOpenId: wxInfo.openid,
          unionid: wxInfo.unionid,
          headimgurl: wxInfo.headimgurl,
          sex: wxInfo.sex,
          city: wxInfo.city,
          province: wxInfo.province,
        }
        requestData = {
          ...requestData,
          ...requestDataWx
        }
      }
      loginOrBindUser(this, requestData, cb)
      
    },
    toGetBindInfo(phone){
      return new Promise(resolve => {
        let requestData = {
          par: phone,
        }
        getBindInfo(requestData, (res) => {
          console.log('手机号是否绑定微信: ', res)
          resolve(res)
        })
      })
    },
    applyBelongAuto(shareUser, cb){
      let requestData = {
        isHasShop: 2,
        isSelfManager: 2,
        userkey: localStorage.getItem('userKey'),
        shopName: this.phone,
        mobile: this.phone,
        mobileCode: 'csyys007titika',
        shopAddress: '浙江省杭州市',
        occupation: '运营商下线',
        isShowLogo: false,
        logoUrl: '',
        parentId: shareUser.UserId,
        isChangeParent: true,
      }
      applyBelong(requestData, () => {
        setTimeout(() => {
          cb && cb()
        },1000)
      })
    },
    getIsISPorBelong(userId) {
      return new Promise((resolve) => {
        getUserDetailById(userId, (userInfo) => {
          // 判断是否是城市运营商
          let isISP = userInfo.IsISP
          let isBelongMan = userInfo.IsDistributor
          localStorage.setItem("isISP", isISP)
          localStorage.setItem('isBelongMan', isBelongMan)
          resolve(userInfo)
        })
      })
    },
    goToRegister(){
      this.$router.push({
        // path: '/registerPhone',
        path: 'forget',
        query: {
          type: 'forget'
        }
      })
    },
  },
}
</script>

<style scoped>
.container{
  background: #ffffff;
}
.form{
  padding: 80px 30px 40px 30px;
}
.form .title{
  font-size: 20px;
  line-height: 1.6;
  padding-bottom: 30px;
}
.form .ipt{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}
.form .ipt input{
  flex-grow: 1;
  height: 50px;
  line-height: 20px;
  font-size: 16px;
  border-bottom: 1px solid #e0e0e0;
}
.form .ipt .country-num{
  color: #ccc;
  height: 50px;
  line-height: 50px;
  padding-right: 10px;
  border-bottom: 1px solid #e0e0e0;
}
.form .ipt-validate{
  position: relative;
}
.form .ipt-validate a{
  position: absolute;
  right: 0;
  top: 5px;
  display: inline-block;
  width: 98px;
  line-height: 40px;
  border-radius: 40px;
  color: #ccc;
  text-align: center;
  font-size: 14px;
  background-color: #f4f4f4;
}
.form-btn{
  margin-top: 50px;
  font-size: 18px;
  text-align: center;
  line-height: 45px;
  color: #ffffff;
  border-radius: 45px;
  opacity: .2;
  background-color: #d50721;
}
.form-btn.btn-bg{
  opacity: 1;
}
.form-btn-new{
  margin-top: 20px;
  opacity: 1;
  background-color: #000;
}
.tips{
  display: block;
  font-size: 16px;
  padding-top: 5px;
  line-height: 3.5;
  color: #0598dd;
  text-align: center;
}
.tabs{
  display: flex;
  align-items: center;
  margin: 30px 30px 0 30px;
  border-bottom: 1px solid #e0e0e0;
}
.tabs .tab{
  position: relative;
  color: #666666;
  flex-grow: 1;
  line-height: 40px;
  text-align: center;
}
.tabs .tab-cur{
  color: #000000;
}
.tabs .tab-cur:after{
  display: block;
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: -1px;
  height: 2px;
  background-color: #d50721;
}
</style>